package com.zmx.patients;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.zmx.patients.fragment.HomeFragment;
import com.zmx.patients.fragment.InformationFragment;
import com.zmx.patients.fragment.MineFragment;
import com.zmx.patients.fragment.PhysicianFragment;
import com.zmx.patients.okhttp.OkHttp3ClientManager;
import com.zmx.patients.pojo.Tab;
import com.zmx.patients.view.util.FragmentTabHost;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import constacne.UiType;
import listener.Md5CheckResultListener;
import listener.UpdateDownloadListener;
import model.UiConfig;
import model.UpdateConfig;
import update.UpdateAppUtils;

public class MainActivity extends BaseActivity {

    private FragmentTabHost mTabhost;
    private LayoutInflater inFlater;
    private List<Tab> mTabs = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViews() {

        UpdateAppUtils.getInstance().deleteInstalledApk();
        initTab();
        handler.sendEmptyMessage(1);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    //检测有没有新版本
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("type", "3");
                    OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/upgrade", params, handler, 2, 404);

                    break;

                case 2:

                    JSONObject object = null;
                    JSONObject data = null;
                    Log.e("升级版本号", "" + msg.obj.toString());
                    try {

                        object = new JSONObject(msg.obj.toString());
                        String s = object.getString("data");
                        data = new JSONObject(s);

                        String edition = data.getString("edition");
                        String url = data.getString("url");
                        String updateContent = data.getString("message");

                        Log.e("当前版本号", "" + packageName(mActivity));
                        Log.e("升级版本号", "" + edition);

                        if (!packageName(mActivity).equals(edition)) {
                            UpdateApp(url, edition,updateContent);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("升级版本号", "错误：" + e.toString());
                    }


                    break;

            }

        }
    };


    private void initTab() {

        Tab home = new Tab("首页", R.drawable.selector_icon_home, HomeFragment.class);
        Tab dynamic = new Tab("社区", R.drawable.selector_icon_hot, InformationFragment.class);
        Tab cart = new Tab("问诊", R.drawable.selector_icon_cart, PhysicianFragment.class);
        Tab mine = new Tab("我的", R.drawable.selector_icon_mine, MineFragment.class);

        mTabs.add(home);
        mTabs.add(dynamic);
        mTabs.add(cart);
        mTabs.add(mine);

        inFlater = LayoutInflater.from(this);
        mTabhost = this.findViewById(R.id.tabhost);
        mTabhost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        for (Tab tab : mTabs) {

            TabHost.TabSpec tabSpec = mTabhost.newTabSpec(tab.getTitle());
            tabSpec.setIndicator(buildIndicator(tab));
            mTabhost.addTab(tabSpec, tab.getFragment(), null);

        }

        //去除分割线
        mTabhost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
        mTabhost.setCurrentTab(0);


    }


    private View buildIndicator(Tab tab) {

        View view = inFlater.inflate(R.layout.tab_indicator, null);
        ImageView img = view.findViewById(R.id.icon_tab);
        TextView text = view.findViewById(R.id.txt_indicator);

        Log.e("底部导航栏",""+tab.getIcon());
        img.setImageResource(tab.getIcon());
        text.setText(tab.getTitle()+"");
        return view;
    }


    //获取当前版本号
    public static String packageName(Context context) {
        PackageManager manager = context.getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }

    //检测更新
    public void UpdateApp(String url, String edition,String updateContent) {

        //检测版本更新
        UpdateConfig updateConfig = new UpdateConfig();
        updateConfig.setCheckWifi(true);
        updateConfig.setNeedCheckMd5(true);
        updateConfig.setNotifyImgRes(R.mipmap.mingyi);
        updateConfig.setForce(true);

        UiConfig uiConfig = new UiConfig();
        uiConfig.setUiType(UiType.PLENTIFUL);

        UpdateAppUtils
                .getInstance()
                .apkUrl(url)
                .updateTitle("发现新版本V" + edition)
                .updateContent(updateContent)
                .uiConfig(uiConfig)
                .updateConfig(updateConfig)
                .setMd5CheckResultListener(new Md5CheckResultListener() {
                    @Override
                    public void onResult(boolean result) {

                    }
                })
                .setUpdateDownloadListener(new UpdateDownloadListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onDownload(int progress) {

                    }

                    @Override
                    public void onFinish() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                })
                .update();

    }


}
